package org.example.sword2offer.primary;

/**
 * @author: lynn
 * @Descript:  https://www.bilibili.com/video/BV1Tr4y1A7SK?from=search&seid=84920622567164998
 *   链表中遇到的问题
 *  Leetcode19.删除链表的倒数第N个节点
 * @date: 2021/7/2 15:36
 * @version: 1.0
 */
public class Q80_DeleteNListNode {
    //bilibi视频 重点会围绕多少个链表类型进行考试
    public static void main(String[] args) {
        ListNode node=new ListNode(0);
        node.next=new ListNode(1);
        node.next.next=new ListNode(2);
        node.next.next.next=new ListNode(3);
        node.next.next.next.next=new ListNode(4);
        Q80_DeleteNListNode deleteNListNode=new Q80_DeleteNListNode();
        deleteNListNode.removeNthFromEnd(node,5);
        System.out.println("");
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {  //fixme Leetcode19.删除链表的倒数第N个节点

        if(head==null||n<1) return null;
        ListNode fastNode=head;
        ListNode slowNode=head;
        while(n>0){
            fastNode=fastNode.next;
            n--;
        }
        //fixme 如果n的值等于链表的长度,直接返回去掉头结点的链表,这个注意下
        if(fastNode==null){
            return head.next;
        }
        //fixme 走到倒数的第n+1个结点
        while(fastNode.next!=null){
            fastNode=fastNode.next;
            slowNode=slowNode.next;
        }
        //fixme 跳过倒数的第n个结点
        slowNode.next=slowNode.next.next;
        return head;
    }

    public static class ListNode{
        ListNode next;
        int val;
        ListNode(int val){
            this.val=val;
        }
    }
}
